import { Application, Session } from "mydog";
import { DEF } from "../../../app/definition/consts";
import { lobby_msg } from "../../../config/proto/lobby";
import lobbyManager from "../../../app/lobbyManager";

export default class Handler {
  private app: Application;
  constructor(app: Application) {
    this.app = app;
  }

  public match(msg: lobby_msg.c2s_match, session: Session, next: Function) {
    const gameMode = msg.gameMode;
    const uid = session.uid;

    const res: lobby_msg.s2c_match = new lobby_msg.s2c_match();

    const user = lobbyManager.getUserById(uid);
    if (!!user && user.isOnline) {
      if (user.roomId !== DEF.ROOM.ID_INVALID) {
        res.code = DEF.SYSTEM.MATCH_CODE.FAIL_ALREADY_IN_ROOM;
        next(res);
        return;
      }

      if (user.matching) {
        res.code = DEF.SYSTEM.MATCH_CODE.FAIL_IS_MATCHING;
        next(res);
        return;
      }

      lobbyManager.startMatching(gameMode, uid);
      res.code = DEF.SYSTEM.MATCH_CODE.SUCCESS;
      next(res);
      return;
    }
    res.code = DEF.SYSTEM.MATCH_CODE.FAIL_USER_ERROR;
    next(res);
  }

  public unmatch(msg: lobby_msg.c2s_unmatch, session: Session) {
    const gameMode = msg.gameMode;
    const uid = session.uid;

    lobbyManager.unmatch(gameMode, uid);
  }
}
